package activator;

//import library.service.LibraryService;

import library.service.LibraryService;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.service.log.LogListener;
import org.osgi.service.log.LogService;
import org.osgi.util.tracker.ServiceTracker;

import service.LibraryLogServiceListener;

public class LibraryLogServiceActivator implements BundleActivator {

	// --- Members -------------------------------------------------------------
	private LibraryService libraryService = null;
	private ServiceTracker libraryServiceTracker = null;
	private LibraryLogServiceListener logListener = null;

	// --- Implementation BundleActivator interface ----------------------------
	public void start(BundleContext context) throws Exception {

		// 1. instantiate LogServiceListener
		logListener = new LibraryLogServiceListener(context);

		// 2. instantiate LibraryService Tracker
		libraryServiceTracker = new ServiceTracker(context,
				LibraryService.class.getName(), null);

		libraryServiceTracker.open();

		// 3. get LibraryService instance from Tracker
		LibraryService libraryService = (LibraryService) libraryServiceTracker
				.getService();

		// 4. consume LibraryService
		libraryService.findBookByName("Java");

		// 5. log some messages
		log(LogService.LOG_INFO, "[LogExample] Info message", null);
		log(LogService.LOG_WARNING, "[LogExample] Warning message",
				new RuntimeException());
		log(LogService.LOG_ERROR, "[LogExample] Error message",
				new RuntimeException());

	}

	public void stop(BundleContext context) throws Exception {

		// 1. log some data
		log(LogService.LOG_INFO, "[LogExample] Stopping LogExample!", null);

		// 2. collect garbage
		logListener.stop();
		libraryServiceTracker.close();
		libraryService = null;
	}

	// --- Methods -------------------------------------------------------------
	void log(int levelType, String message, Throwable throwable) {
		if (logListener.getLog() != null) {
			logListener.getLog().log(levelType, message, throwable);
		} else {
			// LogService of LogListener is NULL

			// 1. print message
			System.out.println("[LOG] " + message);

			// 2. print stackTrace
			if (throwable != null) {
				throwable.printStackTrace();
			}
		}
	}
}
